package org.nimi317.web_gis.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.nimi317.web_gis.Enum.WeatherEnum;
import org.nimi317.web_gis.exception.E;
import org.nimi317.web_gis.exception.RException;
import org.nimi317.web_gis.form.post.WeatherPost;
import org.nimi317.web_gis.entity.AreaWeather;
import org.nimi317.web_gis.entity.R;
import org.nimi317.web_gis.service.IAreaWeatherService;
import org.nimi317.web_gis.service.IStationService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author thunderobot
 */
@RestController
@RequestMapping("weather")
public class Weather {

    private final IAreaWeatherService weatherService;

    private final IStationService stationService;

    public Weather(IAreaWeatherService weatherService, IStationService stationService) {
        this.weatherService = weatherService;
        this.stationService = stationService;
    }

    @PostMapping
    public R<?> getWeather(@RequestBody @Validated WeatherPost post) {
        //获取当前市区气象数据
        LambdaQueryWrapper<AreaWeather> queryWrapper = new LambdaQueryWrapper<>();
        Integer id;
        if (post.getType().equals(WeatherEnum.City)) {
            id = stationService.getById(post.getId()).getCityCode();
            if (ObjectUtil.isNull(id)) {
                throw new RException(E.StationIdNotFoundException);
            }
        } else {
            id = Integer.valueOf(post.getId());
        }
        LambdaQueryWrapper<AreaWeather> wrapper = queryWrapper.eq(AreaWeather::getCityCode, id)
                .orderByDesc(AreaWeather::getPublishTime).last("limit 1");
        AreaWeather weather = weatherService.getOne(wrapper);
        return R.ok(weather);
    }
}
